import { useState, useEffect } from 'react';

type Theme = 'light' | 'dark'

const ThemeToggle = () => {
  const [theme, setTheme] = useState<Theme>(localStorage.getItem('theme') as Theme||'light')

  useEffect(() => {
    localStorage.setItem('theme', theme)
    document.documentElement.className = theme
  }, [theme])

  const toggleTheme = (e: React.MouseEvent) => {
    const x = e.clientX ?? innerWidth / 2;
    const y = e.clientY ?? innerHeight / 2;
    const endRadius = Math.hypot(
      Math.max(x, innerWidth - x),
      Math.max(y, innerHeight - y),
    );
    const clipPath = [
      `circle(0 at ${x}px ${y}px)`,
      `circle(${endRadius}px at ${x}px ${y}px)`,
    ]
    
    // 创建过渡
    const transition = document.startViewTransition(() => {
      setTheme(prev => prev === 'light' ? 'dark' : 'light')
    });

    transition.ready.then(() => {
      document.documentElement.animate(
        {
          clipPath: theme === 'light' ? clipPath : clipPath.reverse()
        },
        {
          duration: 400,
          easing: "ease-in",
          pseudoElement: theme === 'light' ? "::view-transition-new(root)" : "::view-transition-old(root)",
        },
      );
    });
  }

  return (
    <div 
      className="theme-toggle"
      onClick={toggleTheme}
      aria-label={`切换到${theme === 'light' ? '暗色' : '亮色'}主题`}
    >
      {theme === 'light' ? '亮' : '暗'}
    </div>
  )
}

export default ThemeToggle
